package com.hntxk.cqzd.diacrisis.action;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.io.CharStreams;
import com.hntxk.core.framework.model.ResponseModel;
import com.hntxk.core.util.DateUtil;
import com.hntxk.core.util.ModelEntityUtil;
import com.hntxk.core.util.NumberUtil;
import com.hntxk.core.util.StringUtil;
import com.hntxk.cqzd.common.action.CqzdBaseController;
import com.hntxk.cqzd.common.util.CalculateAge;
import com.hntxk.cqzd.diacrisis.entity.TblDiacrisisInfo;
import com.hntxk.cqzd.diacrisis.model.DiacrisisAllModel;
import com.hntxk.cqzd.diacrisis.model.his.*;
import com.hntxk.cqzd.diacrisis.service.DiacrisisInfoService;
import com.hntxk.cqzd.diacrisis.service.impl.DiacrisisInfoServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.Charsets;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.logging.log4j.LogManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

@Api(value="His额外提供接口", tags={"[cqzd]接口"})
@Controller
@RequestMapping("cqzd/do/diacinfo")
@Slf4j
public class DiacrisisInfoController  extends CqzdBaseController {

    private final static String LIST_JSP_PATH = "cqzd/diacrisis/diacrisis_list";

    private final DiacrisisInfoService diacrisisInfoService;



    public DiacrisisInfoController(@Qualifier("diacInfoService") DiacrisisInfoService diacrisisInfoService) {
        super(diacrisisInfoService, LogManager.getLogger(DiacrisisInfoController.class));
        this.diacrisisInfoService = diacrisisInfoService;
    }

    @GetMapping(value = "/index")
    public String index() {


        return LIST_JSP_PATH;
    }

    /**
     * 查询所有历史就诊记录列表
     * @param tblDiacrisisInfo
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/queryAllList",method = {RequestMethod.GET,RequestMethod.POST}, produces= PRODUCE_UTF8_JSON)
    public String queryAllList(@ModelAttribute TblDiacrisisInfo tblDiacrisisInfo){
        ModelEntityUtil.setEmptyStrToNull(tblDiacrisisInfo,false);
        tblDiacrisisInfo.getProp().put("dialect",diacrisisInfoService.getDataBaseDialect());
        if (StringUtils.isNotBlank(tblDiacrisisInfo.getPatientName())){
            tblDiacrisisInfo.setPatientName("%"+tblDiacrisisInfo.getPatientName()+"%");
        }
        tblDiacrisisInfo.setPagination(request);
        return toJson(tblDiacrisisInfo, diacrisisInfoService.query2Json(DiacrisisInfoServiceImpl.DIACINFO_MAPPER_NAMESPACE + "query", tblDiacrisisInfo, false));
    }

    /**
     * 修改就诊记录
     * @param files 文件对象
     * @param json  诊断信息对象
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/updateDiacrisisInfo",produces = PRODUCE_UTF8_JSON)
    @ResponseBody
    public String updateDiacrisisInfo(@RequestParam("file") MultipartFile[] files, @RequestParam("json") String json) throws Exception{

        DiacrisisAllModel diacrisisAllModel= JSON.parseObject(json,DiacrisisAllModel.class);
        if(NumberUtil.isNotNull(diacrisisAllModel.getTblDiacrisisInfo().getDiacrisisId())){
            diacrisisInfoService.update(diacrisisAllModel,files);
            return responseOk();
        }else{
            return responseSorry("被修改数据的id有误");
        }
    }

    /**
     * 手机端新增患者信息
     * @param files 文件对象
     * @param json  诊断信息对象
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/phone/addPhoneDiacrisisInfo",produces = PRODUCE_UTF8_JSON)
    @ResponseBody
    public String insertPhoneDiac(@RequestParam("file") MultipartFile[] files,@RequestParam("json") String json) throws Exception{

        DiacrisisAllModel diacrisisAllModel= JSON.parseObject(json,DiacrisisAllModel.class);
        diacrisisInfoService.insertPhone(diacrisisAllModel,files);
        return responseOk();
    }

    /**
     * 新增患者信息
     * @param files 文件对象
     * @param json  诊断信息对象
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/addDiacrisisInfo",produces = PRODUCE_UTF8_JSON)
    @ResponseBody
    public String insertDiacrisisInfoAndFile(@RequestParam(name="file",required = false) MultipartFile[] files,@RequestParam("json") String json) throws Exception{

        DiacrisisAllModel diacrisisAllModel= JSON.parseObject(json,DiacrisisAllModel.class);
        diacrisisInfoService.insert(diacrisisAllModel,files);
        return responseOk();
    }

    /**
     * 查询患者就诊记录
     * @param key      代表患者姓名、身份证号、就诊卡号
     * @param isValid   是否作废 'null'，代表查询所有  1代表查询有效数据
     * @return
     */
    @RequestMapping(value = "/queryDiacrisisInfo",produces = PRODUCE_UTF8_JSON)
    @ResponseBody
    public ResponseModel queryDiacrisisInfo(@RequestParam(required = false) String key, String isValid){
        return diacrisisInfoService.getAllInfo(key, isValid);
    }

    /**
     * 查询某条诊断信息下的所有数据
     * @param id  诊断信息对象主键id
     * @return
     */
    @RequestMapping(value = "/getDiacrisisInfo/{id}",produces = PRODUCE_UTF8_JSON)
    @ResponseBody
    public String getDiacrisisInfo(@PathVariable Long id){
        return toJson( diacrisisInfoService.getDiacrisisInfo(id));
    }

    /**
     * 查询his中某个对象的数据
     * @param id  his中患者本地id
     * @return
     */
    @RequestMapping(value = "/getHisOne/{id}",produces = PRODUCE_UTF8_JSON)
    @ResponseBody
    public String getHisOne(@PathVariable Long id){
        HisModel hisModel = diacrisisInfoService.getByHisId(id);
            return toJson(hisModel);
    }

    /**
     * 查询his中某个对象的数据 手机端引用
     * @param id  his中患者卡号
     * @return
     */
    @RequestMapping(value = "/phone/getHisOneByCard/{id}",produces = PRODUCE_UTF8_JSON)
    @ResponseBody
    public String getHisOneByCard(@PathVariable String id){
        HisModel hisModel = diacrisisInfoService.getByCardCode(id);
        return toJson(hisModel);
    }

//    @ApiImplicitParam(name = "getCode",value = "查询条件，根据visitNo和起始时间")
    @ApiOperation(value = "查询额外的visitNo")
    @RequestMapping(value = "/getCode",produces = PRODUCE_UTF8_JSON)
    @ResponseBody
    public String getHisByCode(@RequestParam String code,@RequestParam String startDate){
        diacrisisInfoService.getByCode(code,startDate);
        return null;
    }

    /**
     * 获取当天的挂号数据
     * @param key
     * @return
     * @throws
     */
    @RequestMapping(value = "/gethis",produces = PRODUCE_UTF8_JSON)
    @ResponseBody
    public String getHisList(@RequestParam(required = false) String key)  {
        HisModel model=new HisModel();
        if(StringUtil.isNotNull(key)){
            model.setPatientName(key);
        }
        //获取当前时间
        //获取三十天之前的日期
//        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
//        Date startDate = DateUtils.addDays(new Date(), -30);
//        model.setStartDate(DateUtil.getDate(simpleDateFormat.format(startDate)));
//        model.setEndDate(DateUtil.getDate(simpleDateFormat.format(new Date())));
        model.setIsBeoperated('N');
        return toJson(model, diacrisisInfoService.query2Json(DiacrisisInfoServiceImpl.DIACINFO_MAPPER_NAMESPACE + "getHis", model, true,0,10));
    }
    /**模拟测试解析his数据  和程序无关*/
    public static List<HisModel> getHis(HisModel model){
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //获取当前时间
        Date startDate=new Date();
        String format = simpleDateFormat.format(startDate);
        //获取五分钟之后的时间
        Date endDate = new Date(startDate.getTime() + 300000);
        String endFormat = simpleDateFormat.format(endDate);

        String startTime = format.replace(" ", "T");
        String endTime = endFormat.replace(" ", "T");
//        String uri="http://192.168.10.175:7800/EncounterPoint/fhir/Appointment?visitTypeCode=01&registrationDeptCode=0314&startTime=2019-11-18T10:55:25&endTime=2019-11-18T12:00:25";
//        String uri = "http://192.168.10.175:7800/EncounterPoint/fhir/Appointment?visitTypeCode=01&registrationDeptCode=0314&startTime="+startTime+"&endTime="+endTime;
//        if(StringUtil.isNotNull(model.getPatientId())){
//            String patientId = model.getPatientId();
//            uri= "http://192.168.10.175:7800/EncounterPoint/fhir/Appointment?visitTypeCode=01&registrationDeptCode=0314&startTime=2019-11-18T07:40:00&endTime=2019-11-18T08:45:00&cardNo="+ patientId;
//        }
        try {
            HttpClient httpclient = new DefaultHttpClient();
//            String uri = "http://192.168.10.175:7800/EncounterPoint/fhir/Appointment?visitTypeCode=01&registrationDeptCode=0314&startTime=2019-11-18T07:40:00&endTime=2019-11-18T08:45:00";
            String uri = "http://127.0.0.1:8008/commom/file/ceshi";
            HttpGet httpGet = new HttpGet(uri);
            // 添加http头信息
//            Date businessTime = new Date(); // 业务时间，查询接口可不填
            Date operationTime = new Date(); // 调用此接口的系统时间，一般是调用平台接口时new当时时间
            httpGet.addHeader("Content-Type", "application/fhir+json");
            httpGet.addHeader("rootId", "402881f96463c15d016463c368670000"); // 调用方存储日志的id，用于追溯日志
            httpGet.addHeader("token", "0000000378"); // 调用接口中的业务号，例如使用患者流水号查询检验报告接口，此处填写患者就诊流水号
            httpGet.addHeader("businessTime", ""); // 此接口对应的业务时间，如果是查询接口可不填
            httpGet.addHeader("domain", "HIS"); // 调用此接口的系统域，例如LIS、HIS、SPD
            httpGet.addHeader("key", "20d9b12a-37c2-4103-baf8-4760ed47dedb"); // 调用此接口的授权码，与系统域对应，一般是总线维护的授权码
            httpGet.addHeader("operationTime", DateUtil.getStrByFormat( operationTime,"yyyy-MM-dd HH:mm:ss")); // 调用此接口的系统时间，一般是调用平台接口时new当时时间
            HttpResponse response;
            response = httpclient.execute(httpGet);

            // 检验状态码，如果成功接收数据
            InputStream out = response.getEntity().getContent();
            String result = CharStreams.toString(new InputStreamReader(out, Charsets.UTF_8));
            List<HisModel> hisModels=new ArrayList<>();

            //解析数据
            JSONObject jsonObject = JSON.parseObject(result);
            JSONArray entry = (JSONArray) jsonObject.get("entry");
            if(entry!=null&&entry.size()>0) {
                for (int i = 0; i < entry.size(); i++) {
                    HisModel hisModel=new HisModel();
                    JSONObject object = (JSONObject) entry.get(i);
                    if(object!=null) {
                        JSONObject entryJson = (JSONObject) object.get("resource");
                        if (entryJson != null) {
                            Resource resource = JSON.parseObject(entryJson.toJSONString(), Resource.class);

                            if (resource != null) {
                                String value = resource.getIdentifier().get(0).getValue();
                                hisModel.setOutpatientNo(value);
                                if(!"0314".equals(resource.getSpecialty().get(0).getCoding().get(0).getCode())){
                                    continue;
                                }


                                for (int j = 0; j < resource.getParticipant().size(); j++) {

                                    Actor actor = resource.getParticipant().get(j).getActor();
                                    if (actor != null) {
                                        List<Extension> extensions = actor.getExtension();
                                        if(extensions!=null&&extensions.size()>0) {
                                            for (int k = 0; k < extensions.size(); k++) {
                                                if (extensions.get(k).getUrl().indexOf("patientName") != -1) {
                                                    hisModel.setPatientName(extensions.get(k).getValueString());
                                                }
                                                if (extensions.get(k).getUrl().indexOf("patientLocalId") != -1) {
                                                    hisModel.setPatientId(extensions.get(k).getValueString());
                                                }
                                                if (extensions.get(k).getUrl().indexOf("Appointment/card") != -1) {
                                                    ValueCodeableConcept valueCodeableConcept = extensions.get(k).getValueCodeableConcept();
                                                    //获取并设置身份证
                                                    if(valueCodeableConcept.getCoding().get(0).getCode().equals("4")){
                                                        hisModel.setCardTypeId(valueCodeableConcept.getCoding().get(0).getCode());
                                                        hisModel.setCardType(valueCodeableConcept.getCoding().get(0).getDisplay());
                                                        hisModel.setCardCode(valueCodeableConcept.getText());
                                                        hisModel.setPatientCardId(valueCodeableConcept.getText());
                                                    }else{ //获取并设置卡信息
                                                        hisModel.setCardTypeId(valueCodeableConcept.getCoding().get(0).getCode());
                                                        hisModel.setCardType(valueCodeableConcept.getCoding().get(0).getDisplay());
                                                        hisModel.setCardCode(valueCodeableConcept.getText());
                                                    }
                                                }
                                                if (extensions.get(k).getUrl().indexOf("Appointment/birthday") != -1) {
                                                    hisModel.setPatientBirthday(extensions.get(k).getValueDateTime());
                                                    Date patientBirthday = hisModel.getPatientBirthday();
                                                    int ageByBirth = CalculateAge.getAgeByBirth(patientBirthday);
                                                    hisModel.setPatientAge(ageByBirth);

                                                }

                                            }

                                        }
                                    }

                                }
                            }
                        }
                    }
                    hisModels.add(hisModel);
                }

            }

            int code = response.getStatusLine().getStatusCode();

            System.out.println("code:" + code);
            return  hisModels;
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

        public static void main(String[] args) {
        HisModel hisModel=new HisModel();
        List<HisModel> his = getHis(hisModel);

    }

    /**
     * 删除his表一周之前的数据
     * @return
     */
    @RequestMapping(value = "/deleteOneWeek",produces = PRODUCE_UTF8_JSON)
    @ResponseBody
    public String deleteOneWeek(){
        diacrisisInfoService.deleteOneWeek();
        return null;
    }


}
